package com.sea.finance.controller;


import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.Payment;
import com.sea.finance.entity.PaymentAgain;
import com.sea.finance.service.PaymentAgainService;
import com.sea.finance.service.PaymentService;
import com.sea.product.service.ChannelService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/finance/paymentAgain")
public class PaymentAgainController {

    @Autowired
    private PaymentAgainService paymentAgainService;
    @Autowired
    private ChannelService channelService;
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("channel",channelService.findByCnd(null));
        return "/sea/finance/paymentAgain/main";
    }



    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     PaymentAgain paymentAgain) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<PaymentAgain> list = paymentAgainService.findByCnd(paymentAgain);
        PageInfo<PaymentAgain> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }



    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importSku(Model model,
                                MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = file.getInputStream();
                paymentAgainService.importPayment(is,fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, PaymentAgain paymentAgain) {
        List<PaymentAgain> list = paymentAgainService.findByCnd(paymentAgain);
        String[] title = {"时间","SKU","渠道","销量"};
        String fileName = "Payment表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "Payment表";
        String[][] content = new String[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            PaymentAgain obj = list.get(i);
            content[i][0] = obj.getPaymentDate();
            content[i][1] = obj.getPaymentSku();
            content[i][2] = obj.getPaymentChannelName();
            content[i][3] = obj.getPaymentNumber()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
